﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace MyUtils.Core
{
    /// <summary>
    /// 文件常用数据
    /// </summary>
    internal class FileDetail
    {
        /// <summary>
        /// 文件数据
        /// </summary>
        public Dictionary<string, string> FileData { get; set; }
        /// <summary>
        /// 最后写入时间
        /// </summary>
        public DateTime LastWriteTime { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        public FileDetail()
        {
            FileData = new Dictionary<string, string>();
            LastWriteTime = DateTime.MinValue;
        }
    }
    /// <summary>
    /// json读取类
    /// </summary>
    public class JsonReader
    {
        #region 变量定义
        private string _filePath;
        private FileDetail _fileDetail;
        public string FilePath { get { return _filePath; } }
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="filePath">json文件路径</param>
        /// <param name="useCache">是否使用缓存机制</param>
        public JsonReader(string filePath,bool useCache = true)
        {
            _filePath = filePath;
            _fileDetail = useCache ? new FileDetail() : null;
        }
        #endregion

        #region 对外函数
        /// <summary>
        /// eg: JsonReader.Read("appsetting.json","appsettings:database:sqlite")
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string Read(string key)
        {
            string[] levels = key.Split(':');
            if (File.Exists(_filePath))
            {
                if (_fileDetail != null) // 当使用缓存机制时 这个私有变量会被使用
                {
                    var info = new FileInfo(_filePath);
                    var infoLastWriteTime = info.LastWriteTime;
                    if (infoLastWriteTime != _fileDetail.LastWriteTime) // 该文件更新过
                    {
                        if (_fileDetail.FileData.Count > 0)
                            _fileDetail.FileData.Clear();
                    }
                    else
                    {
                        if (_fileDetail.FileData.TryGetValue(key, out var ret)) // 没更新过且内存存在该key
                            return ret;
                    }
                }
                //byte[] data = null;
                var data = File.ReadAllBytes(_filePath);

                if (data != null)
                {
                    string content = Encoding.UTF8.GetString(data);
                    using (var doc = JsonDocument.Parse(content))
                    {
                        var root = doc.RootElement;
                        for (var i = 0; i < levels.Length; i++)
                        {
                            if (root.ValueKind != JsonValueKind.Undefined && root.TryGetProperty($"{levels[i]}", out root)) // 回写 root(层层递进)
                            {
                                if (i == levels.Length - 1)
                                {
                                    var ret = root.ToString();
                                    if (_fileDetail != null)
                                    {
                                        _fileDetail.FileData.Remove(key);
                                        _fileDetail.FileData.TryAdd(key, ret);
                                    }
                                    return ret;
                                }
                            }
                        }
                    }
                }
            }
            return "";
        }
        #endregion
    }

}
